#include <config.h>
#include "adbutils.h"

static inline const gchar* get_devices_shell_path(){
	static gchar *ret = NULL;
	if(ret == NULL){
		if(g_file_test ("./src/get_devices.sh",G_FILE_TEST_IS_REGULAR)){
			ret  = "./src/get_devices.sh";
		}else {
			ret = PACKAGE_DATA_DIR "/get_devices.sh";
		}
	}
	return ret;
}

static inline AdbDevice*
adb_device_new()
{
    return g_new0(AdbDevice,1);
}

void
adb_device_free(AdbDevice*ad)
{
	if(ad == NULL)return;
    g_free(ad->serial);
	g_free(ad->brand);
	g_free(ad->model);
	g_free(ad->os_version);
	g_free(ad);
}

void
adb_device_list_free(GSList *list)
{
	g_slist_foreach (list,adb_device_free,NULL);
}

static void
adb_device_print(AdbDevice*ad)
{
	if(ad == NULL)return;
    g_print("serial  :%s\n",ad->serial);
	g_print("brand   :%s\n",ad->brand);
	g_print("model   :%s\n",ad->model);
	g_print("android :%s\n\n",ad->os_version);
}

static void
adb_device_print_list(GSList*list)
{
	g_list_foreach (list,adb_device_print,NULL);
}

GSList*
adb_device_list()
{
    GSList *ret = NULL;
	gchar *out = NULL;
	gint st = -1;
	if(g_spawn_command_line_sync (get_devices_shell_path(),&out,NULL,&st,NULL) && st == 0){
		GKeyFile *key = g_key_file_new();
		g_key_file_load_from_data (key,out,-1,0,NULL);
		gsize len = 0;
		gchar **vv = g_key_file_get_groups(key,&len);
		if(vv !=NULL ){
            int i=0;
			for(i=0;i<len;i++){
				AdbDevice *ad = adb_device_new();
				ad->serial = g_strdup(vv[i]);
				ad->os_version = g_key_file_get_string(key,vv[i],"ro.build.version.release",NULL);
				ad->model = g_key_file_get_string(key,vv[i],"ro.product.model",NULL);
				ad->brand = g_key_file_get_string(key,vv[i],"ro.product.brand",NULL);
				ret = g_slist_append(ret,ad);
                //g_print("serial:%s\n",vv[i]);
			}
			g_strfreev (vv);
		}
		g_key_file_free (key);
		
	}

	g_free (out);
	//adb_device_print_list(ret);
    return ret;
}

gint
adb_utils_install(const gchar *serial,const gchar *apk,gchar **msg)
{
	gint ret = -1;
	gchar *out = NULL;
	gchar *err = NULL;
	gchar *cmd = g_strdup_printf("adb %s %s install -r %s",
	                             serial && *serial?"-s":"",
	                             serial && *serial?serial:"",
	                             apk
	                             );
	///g_warning("cmd: %s",cmd);
	g_spawn_command_line_sync (cmd,&out,&err,&ret,NULL);
	g_printerr("%s",out);
	if(ret == 0 ){
		ret = -2;
		gchar **vv = g_strsplit_set(out,"\r\n",-1);
		int i=0;
		gchar *tmp_msg = NULL;
		if(vv){
			gchar *pt = NULL;
			for(i=0;vv[i];i++){
				if(vv[i]&&vv[i][0]){
					pt = vv[i];
				}
			}
			if(pt)tmp_msg = g_strdup(pt);
			g_strfreev (vv);
		}
		if(g_str_has_suffix (tmp_msg,"Success")){
			ret = 0;
		}
		if(msg)*msg = tmp_msg;
		else g_free(tmp_msg);
	}
	if(msg&&*msg == NULL)*msg = err;
	else free(err);
	g_free(out);
	g_free(cmd);
	return ret;
}

